﻿using System;
using System.Collections.Generic;
using System.Text;

using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Linq;

namespace System
{
    public class IntArrayJsonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType.Equals(typeof(string));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            try
            {
                List<int> list = serializer.Deserialize<List<int>>(reader);
                if (list == null)
                    return null;
                return string.Join(",", list);
            }
            catch (Exception)
            {
                throw new JsonReaderException("不是有效的数组类型");
            }
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            try
            {
                serializer.Serialize(writer, value.ToString().Split(',', StringSplitOptions.RemoveEmptyEntries).Where(a => int.TryParse(a, out _)).Select(a => int.Parse(a)).ToArray());
            }
            catch
            {
                serializer.Serialize(writer, new int[0]);
            }
        }
    }
}
